package com.gxuwz.medical.web.servlet.role;

import java.io.IOException;
import java.sql.Connection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gxuwz.medical.dao.RoleDao;
import com.gxuwz.medical.database.DbUtil;
import com.gxuwz.medical.domain.role.Role;
import com.gxuwz.medical.tools.ResponseUtil;
import com.gxuwz.medical.tools.StringUtil;

import net.sf.json.JSONObject;

public class RoleSaveServlet extends HttpServlet {

	DbUtil dbUtil = new DbUtil();
	RoleDao roleDao = new RoleDao(); // 用户数据操作类

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		SaveRole(request, response);
	}

	private void SaveRole(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		System.out.println("来到了保存");
		request.setCharacterEncoding("utf-8");

		/**
		 * 接受从前端传递过来的json数据,要注意引入解析json的包
		 */
		String name = request.getParameter("params");
		System.out.println(name);
		JSONObject json = JSONObject.fromObject(name);
		Iterator iter = json.keySet().iterator();
		Map<String, String> map = new HashMap<String, String>();

		System.out.println("map==" + map);
		/**
		 * 解析来自前端页面的值，解析json数组
		 */
		while (iter.hasNext()) {
			String key = (String) iter.next();
			String value = json.getString(key);
			System.out.println("key:" + key + ",value:" + value);
			map.put(key, value);
		}

		String roleid = request.getParameter("roleid");
		String roleName = request.getParameter("roleName");
		String id = request.getParameter("id");
		System.out.println("roleid==" + roleid + ";roleName==" + roleName + ";id==" + id);
		Role role = new Role(roleid, roleName);
		if (!StringUtil.isEmpty(id)) {
			role.setId(Integer.parseInt(id));
		}
		Connection con = null;
		try {
			con = dbUtil.getCon();
			int saveNums = 0;
			JSONObject result = new JSONObject();
			if (!StringUtil.isEmpty(id)) {
				saveNums = roleDao.roleModify(con, role);
			} else {
				saveNums = roleDao.roleAdd(con, role);
			}
			if (saveNums > 0) {
				result.put("success", "true");
			} else {
				result.put("success", "true");
				result.put("errorMsg", "保存失败");
			}
			ResponseUtil.write(response, result);
			;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				dbUtil.closeCon(con);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}
